package com.lottery.ruok.lottrey.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.text.ClipboardManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.TypefaceSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lottery.ruok.lottrey.MyApplication;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.bean.CompleteManualMissionBean;
import com.lottery.ruok.lottrey.ext.GlideExt;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.CompleteManualMissionRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.JoinActivityRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityWeChatQQResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.JoinActivityResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import ui.IToast;
import utils.Utils;

public class AddFriendsChannelDialogAcrivity extends FragmentActivity {
    private static final int QQ = 1;
    private static final int WECHAT = 2;
    ActivityWeChatQQResponse.ListBean mData;
    @BindView(R.id.text_info)
    TextView textInfo;
    @BindView(R.id.et_wechat)
    EditText etWechat;
    @BindView(R.id.wechat_line)
    ImageView wechatLine;
    @BindView(R.id.et_qq)
    EditText etQq;
    @BindView(R.id.qq_line)
    ImageView qqLine;
    @BindView(R.id.commit)
    Button commit;
    @BindView(R.id.window_close)
    ImageButton windowClose;
    private String mMissionId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_add_frieds_layout);
        ButterKnife.bind(this);
        setFinishOnTouchOutside(false);
        getData();
        initView();
    }

    private void getData() {
        mData = (ActivityWeChatQQResponse.ListBean) getIntent().getSerializableExtra("data");
        mMissionId = getIntent().getStringExtra("mission_id");
    }

    private void initView() {
        if (mData == null) {
            return;
        }
        final ArrayList<ActivityWeChatQQResponse.ListBean.InputBean> inputs = mData.getInputs();

        //只有一个size时
        if (inputs.size() == 1) {
            ActivityWeChatQQResponse.ListBean.InputBean inputBean = inputs.get(0);
            int support_id = inputBean.getSupport_id();
            if (support_id == QQ) {
                etQq.setVisibility(View.VISIBLE);
                qqLine.setVisibility(View.VISIBLE);
                textInfo.append("请添加客服");
                textInfo.append(setQQSSB(inputBean.getCustomer_service()));
                textInfo.append(",并留下您的QQ号，以便与您取得联系！");
            } else {
                wechatLine.setVisibility(View.VISIBLE);
                etWechat.setVisibility(View.VISIBLE);
                textInfo.append("请添加客服");
                textInfo.append(setWeChatSSB(inputBean.getCustomer_service()));
                textInfo.append(",并留下您的微信号，以便与您取得联系！");
            }
        }
        //有2 Size时
        if (inputs.size() == 2) {
            ActivityWeChatQQResponse.ListBean.InputBean first = inputs.get(0);
            ActivityWeChatQQResponse.ListBean.InputBean second = inputs.get(1);
            wechatLine.setVisibility(View.VISIBLE);
            etWechat.setVisibility(View.VISIBLE);
            qqLine.setVisibility(View.VISIBLE);
            etQq.setVisibility(View.VISIBLE);
            etWechat.setHint(first.getSupport_id() == WECHAT ? "微信号" : "QQ号");
            etQq.setHint(second.getSupport_id() == WECHAT ? "微信号" : "QQ号");


            if (first.getSupport_id() == second.getSupport_id()) {//都是一样的
                //都是QQ
                if (first.getSupport_id() == QQ) {
                    textInfo.append("请添加客服");
                    textInfo.append(setQQSSB(first.getCustomer_service()));
                    textInfo.append("且");
                    textInfo.append(setQQSSB(second.getCustomer_service()));
                    textInfo.append(",并留下您的QQ号码，以便与您取得联系!");
                } else {//都是微信
                    textInfo.append("请添加客服");
                    textInfo.append(setWeChatSSB(first.getCustomer_service()));
                    textInfo.append("且");
                    textInfo.append(setWeChatSSB(second.getCustomer_service()));
                    textInfo.append(",并留下您的微信号码，以便与您取得联系!");
                }
            } else {//一个QQ一个微信
                if (first.getSupport_id() == QQ) {//第一个是QQ,第二就是微信
                    textInfo.append("请添加客服");
                    textInfo.append(setQQSSB(first.getCustomer_service()));
                    textInfo.append("或");
                    textInfo.append(setWeChatSSB(second.getCustomer_service()));
                    textInfo.append(",并留下您的QQ和微信号，以便与您取得联系！");
                } else {//第一个是微信，第二个是QQ
                    textInfo.append("请添加客服");
                    textInfo.append(setWeChatSSB(first.getCustomer_service()));
                    textInfo.append("或");
                    textInfo.append(setQQSSB(second.getCustomer_service()));
                    textInfo.append(",并留下您的微信和QQ号，以便与您取得联系！");
                }
            }
        }
        textInfo.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @OnClick({R.id.commit, R.id.window_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.commit:
                assistSubmit();
                break;
            case R.id.window_close:
                finish();
                break;
        }
    }

    private void assistSubmit() {
        if (mData == null) {
            return;
        }
        RequestBody body = null;

        if (mData.getInputs().size() == 1) {//只有一个
            if (!etQq.getText().toString().equals("") || !etWechat.getText().toString().equals("")) {
                body = new FormBody.Builder()
                        .add("mission_id", mMissionId)
                        .add("detail[0][support_id]", mData.getInputs().get(0).getSupport_id() + "")
                        .add("detail[0][task_id]", mData.getTask_id() + "")
                        .add("detail[0][value]", etWechat.getText().toString().equals("") ? etQq.getText().toString() : etWechat.getText().toString())
                        .build();
            }

        } else {//有2个
            if (!etQq.getText().toString().equals("") && !etWechat.getText().toString().equals("")) {
                body = new FormBody.Builder()
                        .add("mission_id", mMissionId)
                        .add("detail[0][support_id]", mData.getInputs().get(0).getSupport_id() + "")
                        .add("detail[0][task_id]", mData.getTask_id() + "")
                        .add("detail[0][value]", etWechat.getText().toString())
                        .add("detail[1][support_id]", mData.getInputs().get(1).getSupport_id() + "")
                        .add("detail[1][task_id]", mData.getTask_id() + "")
                        .add("detail[1][value]", etQq.getText().toString())
                        .build();
            }
        }
        if (body == null)
            return;
        RetrofitBase.getRetrofit().create(CompleteManualMissionRequest.class)
                .getResult(UserInfo.getToken(), body)
                .compose(RxHelper.<JoinActivityResponse>handleResult())
                .subscribe(new RxSubscribe<JoinActivityResponse>(this) {
                    @Override
                    protected void _onNext(JoinActivityResponse joinActivityResponse) {
                        IToast.showDialog(MyApplication.getApplication(), getResources().getString(R.string.missions_help_succsess), R.mipmap.bigok_white);
                        finish();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }

    /**
     * qq spannable配置
     *
     * @param qq
     * @return
     */
    private SpannableString setQQSSB(final String qq) {
        String qqNumber = "QQ" + qq;
        SpannableString QQSSB = new SpannableString(qqNumber);
        QQSSB.setSpan(new ForegroundColorSpan(Color.RED), 0, qqNumber.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        QQSSB.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(qq);
                try {
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mobileqq");
                    startActivity(intent);
                    IToast.showCopySuccess(AddFriendsChannelDialogAcrivity.this);
                } catch (Exception e) {
                    Utils.showToast("请检查是否安装QQ");
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.RED);
                ds.setUnderlineText(false);    //去除超链接的下划线
            }
        }, 0, QQSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return QQSSB;
    }

    /**
     * qq spannable配置
     *
     * @param wechat
     * @return
     */
    private SpannableString setWeChatSSB(final String wechat) {
        String wechatNumber = "微信" + wechat;
        SpannableString weChatSSB = new SpannableString(wechatNumber);
        weChatSSB.setSpan(new ForegroundColorSpan(Color.RED), 0, wechatNumber.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        weChatSSB.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(wechat);
                try {
                    Intent intent = new Intent();

                    ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");

                    intent.setAction(Intent.ACTION_MAIN);

                    intent.addCategory(Intent.CATEGORY_LAUNCHER);

                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    intent.setComponent(cmp);

                    startActivity(intent);
                    IToast.showCopySuccess(AddFriendsChannelDialogAcrivity.this);

                } catch (Exception e) {
                    Utils.showToast("请检查是否安装微信");
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.RED);
                ds.setUnderlineText(false);    //去除超链接的下划线
            }
        }, 0, weChatSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return weChatSSB;
    }
}
